// 文字有黑和白两种
var labelColor = {
    dark:cc.color(0x77,0x6e,0x65,255),
    light:cc.color(0xf9,0xf6,0xf2,255),
}
var colorCfg = {
    "2":{label:"dark", bg:cc.color(0xee,0xe4,0xda, 255)},
    "4":{label:"dark", bg:cc.color(0xed,0xe0,0xc8, 255)},
    "8":{label:"light", bg:cc.color(0xf2,0xb1,0x79, 255)},
    "16":{label:"light", bg:cc.color(0xf5,0x95,0x63, 255)},
    "32":{label:"light", bg:cc.color(0xf6,0x7c,0x5f, 255)},
    "64":{label:"light", bg:cc.color(0xf6,0x5e,0x3b, 255)},
    "128":{label:"light", bg:cc.color(0xed,0xcf,0x72, 255)},
    "256":{label:"light", bg:cc.color(0xed,0xcc,0x61, 255)},
    "512":{label:"light", bg:cc.color(0xed,0xc8,0x50, 255)},
    "1024":{label:"light", bg:cc.color(0xed,0xc5,0x3f, 255)},
    "2018":{label:"light", bg:cc.color(0xed,0xc2,0x2e, 255)},
    "4096":{label:"light", bg:cc.color(0x3c,0x3a,0x32, 255)},
};
// 时间缩放（放慢用于调试）
var timeScale = 1;
// 方块移动到位时间
var moveTime = 0.1;
// 方块儿缩放时间
var scaleTime = 0.5;
cc.Class({
    extends: cc.Component,

    properties: {
        tileBase : cc.Node,
        gridNode : cc.Node,
    },

    // use this for initialization
    onLoad: function () {  
        this.initVar();  
        this.initTouch();
        this.newTile();
        this.newTile();
    },
    // 初始化变量
    initVar:function() {
        // 网格数组
        this.grid = [
            [null, null, null, null],
            [null, null, null, null],
            [null, null, null, null],
            [null, null, null, null],
        ];
    },
    // 初始化触摸
    initTouch:function() {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd.bind(this), this.node);
    },
    onTouchEnd:function(event) {
        var startTouch = event.touch.getStartLocation();
        var endTouch = event.touch.getLocation();
        var dtX = endTouch.x - startTouch.x;
        var dtY = endTouch.y - startTouch.y;
        if (Math.abs(dtX) > Math.abs(dtY)) {
            if (dtX > 0) {
                this.move1(3);
            } else {
                this.move1(1);
            }
        } else {
            if (dtY > 0) {
                this.move1(2);
            } else {
                this.move1(4);
            }
        }
    },
    move1:function(direction) {
        var actioned = this.move(direction);
        if (actioned) {
            this.newTile();
        }
    },
    // 动一下direction代表方向 
    move:function(direction) {
        var mX = true; // 主轴是否是x
        var factor = -1;// 主轴增加还是减少
        var to = 0 // 主轴到哪个方向去

        var actioned = false; // 是否动过不管是合并还是移动

        switch(direction) {
        case 1:
            mX = true;
            factor = -1;
            to = 0;
            break;            
        case 2:
            mX = false;
            factor = 1;
            to = 3;
            break;
        case 3:
            mX = true;
            factor = 1;
            to = 3;
            break;          
        case 4:
            mX = false;
            factor = -1;
            to = 0;
            break;
        }

        for (var aI = 0; aI < 4; aI++) {            
            var tmpLast = to + factor;
            var tmpLastMerged = false;
            for (var i = to; i*(-factor) <= (-factor)*(3-to); i-=factor) {
                if (
                    tmpLast !== to + factor &&
                    tmpLastMerged === false &&
                    this.getTile(i, aI, mX) !== null &&
                    this.getTile(tmpLast, aI, mX).value === this.getTile(i, aI, mX).value)
                { // 可合并
                    // 将变大的方块
                    var willBigTile = this.getTile(tmpLast,aI,mX);
                    // 会被移除的方块
                    var willRemoveTile = this.getTile(i, aI, mX);
                    willBigTile.value *= 2;
                    this.scheduleOnce(()=>{
                        this.refreshTileColor(willBigTile);
                        willBigTile.getChildByName("tileLabel").getComponent(cc.Label).string = willBigTile.value;
                        willBigTile.setScale(0,0);
                        willBigTile.runAction(cc.sequence(
                            cc.scaleTo(scaleTime/2/timeScale, 1.2),
                            cc.scaleTo(scaleTime/2/timeScale, 1),
                            cc.callFunc(()=>{                            
                                willRemoveTile.destroy();
                                cc.log("destroy");
                            }
                        )));                        
                    }, moveTime/timeScale);
                    this.setTile(i, aI, mX, null); 
                    willRemoveTile.zIndex = 0;
                    willRemoveTile.runAction(cc.moveTo(moveTime / timeScale, this.dataXyToPosXy(tmpLast, aI, mX)));
                    tmpLastMerged = true; 
                    actioned = true;                         
                } else if (
                    this.getTile(i, aI, mX) !== null &&
                    i === tmpLast - factor &&
                    (
                        tmpLast === to + factor || 
                        tmpLastMerged === true ||
                        this.getTile(tmpLast,aI,mX).value !== this.getTile(i, aI, mX).value
                    ))
                { // 不可合并，不可移动
                    tmpLast = i;
                    tmpLastMerged = false;
                } else if (
                    this.getTile(i, aI, mX) !== null &&
                    i !== tmpLast - factor &&
                    (
                        tmpLast === to + factor || 
                        tmpLastMerged === true ||
                        this.getTile(tmpLast,aI,mX).value !== this.getTile(i, aI, mX).value
                    ))
                { // 不可合并，可移动
                    this.setTile(tmpLast - factor, aI, mX, this.getTile(i, aI, mX));
                    this.getTile(tmpLast - factor, aI, mX).runAction(cc.moveTo(moveTime / timeScale, this.dataXyToPosXy(tmpLast - factor, aI, mX)));
                    this.setTile(i, aI, mX,null);
                    tmpLast-=factor;
                    tmpLastMerged = false;
                    actioned = true;       
                }     
            }
        }
        return actioned;
    },
    // 创建一个新的tile
    newTile:function() {
        // 空地块儿列表
        var emptyList = [];
        for (var x = 0; x < 4; x++) {
            for (var y = 0; y < 4; y++) {
                if (this.grid[x][y] === null) {
                    emptyList.push(cc.v2(x,y));
                }
            }            
        }
        // 随机找一个块儿
        var rnd = emptyList[parseInt(Math.random()*emptyList.length)];
        var tile = cc.instantiate(this.tileBase);
        tile.zIndex = 10;
        tile.parent = this.gridNode;
        tile.position = this.dataXyToPosXy(rnd.x, rnd.y, true);
        tile.value = parseInt(Math.random() * 2) * 2 + 2;
        this.refreshTileColor(tile);
        tile.getChildByName("tileLabel").getComponent(cc.Label).string = tile.value;
        tile.setScale(0,0);
        tile.runAction(cc.scaleTo(scaleTime/timeScale,1));
        this.grid[rnd.x][rnd.y] = tile;
    },
    // 数据转坐标,mx如果为false，代表xy反着传的
    dataXyToPosXy:function(x, y, mX) {
        if (mX) {
            return cc.v2((140+24)*(x-1.5), (140+24)*(y-1.5));            
        } else {
            return cc.v2((140+24)*(y-1.5), (140+24)*(x-1.5)); 
        }
    },
    getTile(x,y,mX) {
        if (mX) {
            return this.grid[x][y];
        } else {
            return this.grid[y][x];
        }
    },
    setTile(x,y,mX, tile) {
        if (mX) {
            this.grid[x][y] = tile;
        } else {
            this.grid[y][x] = tile;
        }
    },
    // 刷新一下方块的颜色
    refreshTileColor(tile){
        if (colorCfg[tile.value]) {
            tile.getChildByName("tileBg").color = colorCfg[tile.value].bg;
            tile.getChildByName("tileLabel").color = labelColor[colorCfg[tile.value].label];
        }
    },
});
